package cn.edu.swu.bc.servlet;

import cn.edu.swu.bc.filter.AuthFilter;
import cn.edu.swu.bc.utils.DBUtils;
import cn.edu.swu.bc.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1198763434511986380L;


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username = request.getParameter("user");//获取账号密码和验证码
        String pass = request.getParameter("pass");
        String code = request.getParameter("code");
        String errorMsg = null;
        if (username != "" && pass != "" && code != "") {
            String password = null;
            HttpSession session = request.getSession(true);
            User user = new User();
            //从session中取出验证码
            String validateCode = (String) session.getAttribute(AuthFilter.LOGIN_VALIDATE_CODE);
            try {
                user = DBUtils.GetUser(username);
                password = user.getPassword();
                //通过数据库返回用户类
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            if (password != null && password.equals(pass) && validateCode.equalsIgnoreCase(code)) {
                response.sendRedirect("./u/index.html");
                //若登录成功则更改FILTER里的信息
                session.setAttribute(AuthFilter.USER_ID, user.getID());
                session.setAttribute(AuthFilter.USER_NICKNAME, user.getNikcname());
                session.setAttribute(AuthFilter.USER_AVATAR, user.getAvatar());
                session.setAttribute(AuthFilter.USER_SIGNATURE, user.getSignature());
                session.setAttribute(AuthFilter.LOGIN_STATUS, Boolean.TRUE);
                session.setAttribute(AuthFilter.IS_ADMIN, Boolean.FALSE);
                return;
                //判断为那种登录错误并构造错误信息
            } else if (password == null) {
                errorMsg = "该用户不存在";
            } else if (!password.equals(pass)) {
                errorMsg = "账号或密码错误";
            } else {
                errorMsg = "验证码错误";
            }
        } else if (username != "" && pass != "") {
            errorMsg = "请输入验证码";
        } else {
            errorMsg = "请输入用户名和密码";
        }
        request.setAttribute("errorMsg", errorMsg);
        request.getRequestDispatcher("./login.jsp").forward(request, response);
    }
}
